<?

class Auth
{
	private $CI;
	
	public function __construct()
	{
		$this->CI =& get_instance();
	}
	
	public function check()
	{
		if(!$this->is_user()) {
			flash('Please log in to continue');
			redirect($this->CI->config->item('auth_access_denied_location'));
		}
	}
	
	public function is_user()
	{
		return $this->CI->session->userdata('user_id') ? true : false;
	}
	
	public function logout()
	{
		$userdata = array(
			'user_id' => '',
			'user_name' => '',
			'user_password' => '',
			'user_email' => '',
			'fk_role_id' => ''
		);
		
		$this->CI->session->unset_userdata($userdata);
		
		flash('You have successfully logged out.');
		redirect($this->CI->config->item('auth_logout_location'));
	}
	
	public function login($user_email, $password)
	{
		$user = $this->CI->db->get_where('users', array(
			'user_email' => $user_email,
			'user_password' => sha1(
				$this->CI->config->item('auth_pass_salt1') . 
				$password . 
				$this->CI->config->item('auth_pass_salt2')
			),
			'email_verified' => true
		))->row_array();
		
		if($user) 
		{
			$this->CI->session->set_userdata($user);
			flash('You have successfully logged in.');

			redirect($this->CI->config->item('auth_user_login_success_location'));
		} 
		else
		{
			flash('Invalid user name and/or password, or your e-mail address has not yet been verified.');
			redirect($this->CI->config->item('auth_login_fail_location'));
		} 
	}
}